package com.dot.dominion.database;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;

import android.content.res.Resources;
import android.util.Log;

import com.dot.dominion.domain.Card;

/****************** DOES NOT HANDLE ACTION CARDS PROPERLY ********************/
public class CardDatabase {
	private InputStream iStream;
	private ArrayList<String> requestList;	//List of card names requested
	private List<Card> cardList;			//List of actual cards
	
	/**
	 * Main constructor
	 * 
	 * Initializes the request list to contain names in lower case. This is
	 * to simplify the List comparisons
	 * 
	 * @param listOfRequests	List of card names to fetch from the database
	 */
	public CardDatabase( Resources resources, int databaseId,
			List<String> listOfRequests ) {
		requestList = new ArrayList<String>();
		cardList = null;
		
		iStream = resources.openRawResource( databaseId );
		
		if( listOfRequests == null )
			requestList = null;
		//Initialize request list elements to lower case
		while( listOfRequests.size() > 0 )
			requestList.add( (listOfRequests.remove(0)).toLowerCase() );
		
		Log.d("DEBUGTAG", "CardDatabase constructor");
	}
	
	/**
	 * Parses card database and creates list of game cards.
	 * 
	 * Uses the SAX Parser for XML files. It parses the database, first
	 * checking for names. If the name is a requested card, we pull the
	 * remaining information and create a Card from it. Otherwise, we 
	 * don't bother storing the given data and continue parsing.
	 */
	public void createCardList() {
		try {
			/* * *   Setup Constructors   * * */
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			
			DatabaseHandler handler = new DatabaseHandler(requestList);
			
			//Set the proper file streams
			Reader reader = new InputStreamReader(iStream, "UTF-8");
			InputSource iSource = new InputSource( reader );
			iSource.setEncoding("UTF-8");
			
			//Execute and parse the card database
			saxParser.parse(iSource, handler);
			
			cardList = handler.getCardList();
			
		} catch( Exception e ) {
			//Catch the exceptions and print the Stack Trace
			e.printStackTrace();
		}
	}
	

	/*** Supposed to be able to access outside class
	 *** Currently, does not work as expected
	 ***/
	public List<Card> getCardList(String[] listOfRequests) {
		requestList = new ArrayList<String>();
		
		for( int i = 0; i < listOfRequests.length; i++ )
			requestList.add( (listOfRequests[i]).toLowerCase() );
		
		return getCardList();
	}
	
	/**
	 * Get the game card list
	 * 
	 * @return	cardList	The list of actual cards used for play
	 */
	public List<Card> getCardList() {
		if( cardList == null )
			createCardList();
		
		return cardList;
	}
}
